﻿using System;
using ch07.binary;
using ch07.binary.interpreter;
using ch07.binary.wasm_reader;
using ch07.cmd;

namespace ch07
{
    internal static class Program
    {
        public static void Main(params string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: wasmgo [-d] filename");
                Environment.Exit(0);
            }

            if (args[0] == "-d")
            {
                var (module, err) = WasmReader.DecodeFile(args[1]);
                if (err == null)
                {
                    Dumper.Dump(module);
                }
                else
                {
                    Console.WriteLine(err);
                }
            }
            else
            {
                var (module, err) = WasmReader.DecodeFile(args[0]);
                if (err == null)
                {
                    ExecMainFunc(ref module);
                }
                else
                {
                    Console.WriteLine(err);
                }
            }
        }

        private static void ExecMainFunc(ref Module module)
        {
            var idx = (int) (module.StartSec) - (module.ImportSec.Length);
            var vm = new Vm(module);
            vm.InitMem();
            vm.InitGlobals();
            Instr.Call(ref vm, module.StartSec);
            vm.Loop();
        }
    }
}